package com.ysd.lis.service.bak.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.lis.dto.lab.MaininfoDto;
import com.ysd.lis.dto.lab.WorkMainInfoDto;
import com.ysd.lis.entity.PubEmployee;
import com.ysd.lis.entity.SysOrgDepartment;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacCultureCombinaRel;
import com.ysd.lis.entity.bac.BacCultureMedium;
import com.ysd.lis.entity.bac.BacReqPurpose;
import com.ysd.lis.entity.bac.BacReqPurposeSampletype;
import com.ysd.lis.entity.bak.LabMaininfoBak;
import com.ysd.lis.entity.bak.LabReqMainBak;
import com.ysd.lis.entity.bak.LabReqdetailBak;
import com.ysd.lis.entity.bak.LabRptresultBak;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.mapper.bak.LabMaininfoBakMapper;
import com.ysd.lis.mapper.bak.LabRptresultBakMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.lab.LabMapperItemMapper;
import com.ysd.lis.mapper.lab.LabRptresultMapper;
import com.ysd.lis.request.LabMaininfoPageDto;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysUserService;
import com.ysd.lis.service.bak.LabMaininfoBakService;
import com.ysd.lis.service.bak.LabRptresultBakService;
import com.ysd.lis.service.lab.LabRptresultService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 检验上机主表 服务实现类
 * </p>
 *
 * @author WH
 * @since 2024-11-26
 */
@Service
public class LabMaininfoBakServiceImpl extends ServiceImpl<LabMaininfoBakMapper, LabMaininfoBak> implements LabMaininfoBakService {

    @Autowired
    LabMaininfoBakService labMaininfoBakService;

    @Autowired
    LabMaininfoBakMapper labMaininfoBakMapper;

    @Autowired
    LabRptresultBakMapper labRptresultBakMapper;

    @Autowired
    LabRptresultBakService labRptresultBakService;

    @Autowired
    SysBasDictDetailService sysBasDictDetailService;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    LabRptresultMapper labRptresultMapper;

    @Autowired
    LabRptresultService labRptresultService;

    @Autowired
    LabMapperItemMapper labMapperItemMapper;

    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    private DataSource dataSource;

    @Override
    public Result findHisStoryLabMaininfoList(LabMaininfoPageDto maininfoPageDto) {
        MPJLambdaWrapper<LabMaininfoBak> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabMaininfoBak.class);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getBusinessType, LabMaininfoBak::getBusinessType);
        lambdaQueryWrapper.selectAs(LabSampleType::getSampleTypeName, LabMaininfoBak::getSampleTypeNa);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabMaininfoBak::getReqDeptNa);
        //lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabMaininfoBak::getReqDoctorNa);
        lambdaQueryWrapper.selectAs("rptgrp", LabRptGroup::getRptGroupName, LabMaininfoBak::getRptGroupNa);
        lambdaQueryWrapper.leftJoin(LabSampleType.class, on -> on.eq(LabSampleType::getSampleTypeCode, LabMaininfoBak::getSampleType).eq(LabSampleType::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, on -> on.eq(SysOrgDepartment::getCode, LabMaininfoBak::getReqDept).eq(SysOrgDepartment::getDelFlag, 0));
        //lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", on -> on.eq(PubEmployee::getCode, LabMaininfoBak::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(LabRptGroup.class, "rptgrp", LabRptGroup::getRptGroup, LabMaininfoBak::getRptGroup);
        lambdaQueryWrapper.leftJoin(LabReqMainBak.class, LabReqMainBak::getReqNo, LabMaininfoBak::getReqNo);
        if (CollectionUtil.isNotEmpty(maininfoPageDto.getFeeCodes())) {
            lambdaQueryWrapper.leftJoin(LabReqdetailBak.class, LabReqdetailBak::getReqNo, LabMaininfoBak::getReqNo);
        }
        if (CollectionUtil.isNotEmpty(maininfoPageDto.getFeeCodes())) {
            lambdaQueryWrapper.in(LabReqdetailBak::getFeeCode, maininfoPageDto.getFeeCodes());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatId()), LabReqMainBak::getPatId, maininfoPageDto.getPatId());

        lambdaQueryWrapper.eq(LabMaininfoBak::getDelFlag, 0);
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getRptGroup()), LabMaininfoBak::getRptGroup, maininfoPageDto.getRptGroup());
        if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
            Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
            Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
            lambdaQueryWrapper.ge(LabMaininfoBak::getSampleda, startTime);
            lambdaQueryWrapper.le(LabMaininfoBak::getSampleda, endTime);
        }
        if (StringUtils.isNotBlank(maininfoPageDto.getReqNoS()) && StringUtils.isNotBlank(maininfoPageDto.getReqNoE())) {
            lambdaQueryWrapper.ge(LabMaininfoBak::getReqNo, maininfoPageDto.getReqNoS());
            lambdaQueryWrapper.le(LabMaininfoBak::getReqNo, maininfoPageDto.getReqNoE());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabMaininfoBak::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabMaininfoBak::getPatNo, maininfoPageDto.getPatNo());


        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabMaininfoBak::getPatNa, maininfoPageDto.getPatNa()).or().like(LabMaininfoBak::getPatPyName, maininfoPageDto.getPatNa().toLowerCase()));
        }

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getSex()), LabMaininfoBak::getSex, maininfoPageDto.getSex());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabMaininfoBak::getBedNo, maininfoPageDto.getBedNo());
        if (StringUtils.isNotBlank(maininfoPageDto.getSamplingTime())) {
            Timestamp samplingStart = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 00:00:00");
            Timestamp samplingEnd = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 23:59:59");
            lambdaQueryWrapper.ge(LabMaininfoBak::getSamplingTime, samplingStart);
            lambdaQueryWrapper.le(LabMaininfoBak::getSamplingTime, samplingEnd);
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getFeeType()), LabMaininfoBak::getFeeType, maininfoPageDto.getFeeType());
        lambdaQueryWrapper.eq(Objects.nonNull(maininfoPageDto.getIsChk()), LabMaininfoBak::getIsChk, maininfoPageDto.getIsChk());
        lambdaQueryWrapper.eq(Objects.nonNull(maininfoPageDto.getIsPrint()), LabMaininfoBak::getIsPrint, maininfoPageDto.getIsPrint());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabMaininfoBak::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDoctor()), LabMaininfoBak::getReqDoctor, maininfoPageDto.getReqDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTestDoctor()), LabMaininfoBak::getTestDoctor, maininfoPageDto.getTestDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getChkDoctor()), LabMaininfoBak::getChkDoctor, maininfoPageDto.getChkDoctor());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatType()), LabMaininfoBak::getPatType, maininfoPageDto.getPatType());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTraits()), LabMaininfoBak::getTraits, maininfoPageDto.getTraits());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getTestPurpose()), LabMaininfoBak::getTestPurpose, maininfoPageDto.getTestPurpose());

        //过滤无条码
        if (Objects.nonNull(maininfoPageDto.getIsFilterNoSpecCode()) && maininfoPageDto.getIsFilterNoSpecCode()) {
            lambdaQueryWrapper.isNotNull(LabMaininfoBak::getReqNo);
        }
        List<LabMaininfoBak> labMaininfoPage = labMaininfoBakService.list(lambdaQueryWrapper);

        //获取数据字典(病人类型、性别、证件类型)
        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        List<SysUser> userList = sysUserService.list();

        for (LabMaininfoBak maininfo : labMaininfoPage) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
            if (StrUtil.isNotEmpty(maininfo.getChkDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getChkDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setChkDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getTestDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getTestDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setTestDoctorNa(first.get().getRealname());
                }
            }
            if (StrUtil.isNotEmpty(maininfo.getPrintDoctor())) {
                Optional<SysUser> first = userList.stream().filter(a -> maininfo.getPrintDoctor().equals(a.getUsername())).findFirst();
                if (first.isPresent()) {
                    maininfo.setPrintDoctorNa(first.get().getRealname());
                }
            }
        }

        return Result.succ(1, "查询成功", labMaininfoPage);
    }

    @Override
    public Result findHisStoryRptResultByLabMaininfo(LabMaininfo labMaininfo) {

        Timestamp startTime1 = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 00:00:00");
        Timestamp endTime1 = Timestamp.valueOf(labMaininfo.getSampleda().toString().substring(0, 10) + " 23:59:59");


        LambdaQueryWrapper<LabMaininfoBak> queryMI = new LambdaQueryWrapper<>();
        queryMI.eq(LabMaininfoBak::getDelFlag, 0);
        queryMI.eq(LabMaininfoBak::getRptGroup, labMaininfo.getRptGroup());
        queryMI.ge(LabMaininfoBak::getSampleda, startTime1);
        queryMI.le(LabMaininfoBak::getSampleda, endTime1);
        queryMI.eq(LabMaininfoBak::getSampleNo, labMaininfo.getSampleNo());
        LabMaininfoBak miEntry = labMaininfoBakMapper.selectOne(queryMI);
        if (BeanUtil.isEmpty(miEntry)) {
            return Result.succ(1, "查无上机记录", "");
        }

        MPJLambdaWrapper<LabRptresultBak> queryWrapper = new MPJLambdaWrapper<>();

        queryWrapper.distinct().selectAll(LabRptresultBak.class);
        queryWrapper.selectAs("instr", LabInstrSetup::getInstrName, LabRptresultBak::getInstrNa);
        queryWrapper.selectAs("dict", LabItemDict::getUnit, LabRptresultBak::getItemUnit);
        queryWrapper.selectAs("dict", LabItemDict::getSeq, LabRptresultBak::getDisplayOrder);
        queryWrapper.selectAs("dict", LabItemDict::getIsCalcItem, LabRptresultBak::getIsCalcItem);
        queryWrapper.selectAs("dict", LabItemDict::getId, LabRptresultBak::getItemDictId);
        queryWrapper.innerJoin(LabItemDict.class, "dict", p -> p.eq(LabItemDict::getItemNo, LabRptresultBak::getItemNo).eq(LabItemDict::getRptGroup, LabRptresultBak::getRptGroup).eq(LabItemDict::getDelFlag, 0));
        queryWrapper.leftJoin(LabInstrSetup.class, "instr", p -> p.eq(LabInstrSetup::getRptGroup, LabRptresultBak::getRptGroup).eq(LabInstrSetup::getInstrCode, LabRptresultBak::getInstrCode).eq(LabInstrSetup::getDelFlag, 0));
        queryWrapper.eq(LabRptresultBak::getDelFlag, 0);
        Timestamp timestamp = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp timestamp1 = new Timestamp(miEntry.getSampleda().getTime());
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate1 = sdf1.format(timestamp1);
        Timestamp endTime = Timestamp.valueOf(formattedDate1 + " 23:59:59");
        queryWrapper.ge(LabRptresultBak::getSampleda, startTime);
        queryWrapper.le(LabRptresultBak::getSampleda, endTime);
        queryWrapper.eq(LabRptresultBak::getRptGroup, miEntry.getRptGroup());
        queryWrapper.eq(LabRptresultBak::getSampleNo, miEntry.getSampleNo());
        queryWrapper.orderByAsc(LabRptresultBak::getDisplayOrder);
        List<LabRptresultBak> labRptresults = labRptresultBakMapper.selectList(queryWrapper);

        if (!labRptresults.isEmpty()) {
            List<LabRptresultBak> collect = labRptresults.stream().filter(a -> StringUtils.isBlank(a.getMaininfoId())).collect(Collectors.toList());
            for (LabRptresultBak m : collect) {
                m.setMaininfoId(miEntry.getId());
            }
            labRptresultBakService.updateBatchById(collect);
        }

        return Result.succ(1, "查询结果成功", labRptresults);
    }

    @Override
    public Result resultMerge(LabMaininfo labMaininfo) {

        LambdaQueryWrapper<LabRptresult> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabRptresult::getDelFlag, 0)
                .eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup())
                .eq(LabRptresult::getSampleNo, labMaininfo.getSampleNo())
                .eq(LabRptresult::getSampleda, labMaininfo.getSampleda());
        List<LabRptresult> rptresultList = labRptresultMapper.selectList(wrapper);

        MPJLambdaWrapper<LabRptresult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.distinct().selectAll(LabRptresult.class);
        queryWrapper.leftJoin(LabMaininfo.class, p -> p.eq(LabMaininfo::getRptGroup, LabRptresult::getRptGroup)
                        .eq(LabMaininfo::getSampleda, LabMaininfo::getSampleda)
                        .eq(LabMaininfo::getSampleNo, LabRptresult::getSampleNo)
                        .eq(LabMaininfo::getDelFlag, 0))
                .eq(LabRptresult::getSampleda, labMaininfo.getSampleda())
                .eq(LabRptresult::getRptGroup, labMaininfo.getRptGroup())
                .ne(LabRptresult::getSampleNo, labMaininfo.getSampleNo())
                .eq(LabMaininfo::getPatNo, labMaininfo.getPatNo())
                .and(p -> p.eq(LabMaininfo::getIsChk, new BigDecimal(0)).or().isNull(LabMaininfo::getIsChk));

        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);

        //根据rptresultList的itemNo查出LabMapperItem表的关联数据
        List<String> itemNoList = rptresultList.stream().map(LabRptresult::getItemNo).distinct().collect(Collectors.toList());
        List<LabMapperItem> labMapperItems = labMapperItemMapper.selectList(new LambdaQueryWrapper<LabMapperItem>().eq(LabMapperItem::getDelFlag, 0).in(LabMapperItem::getItemNo, itemNoList));

        //对比labMapperItems的mapperItemCode 和 labRptresults 的itemNo如果相同 则收集成一个新的集合
        List<LabRptresult> list = labRptresults.stream()
                .filter(item -> labMapperItems.stream()
                        .anyMatch(labMapperItem -> labMapperItem.getMapperItemCode().equals(item.getItemNo())))
                .collect(Collectors.toList());

        // for (LabRptresult labRptresult : rptresultList){
        //     // 获取labRptresults中的所有itemNo
        //     List<String> itemNos = labRptresults.stream()
        //             .map(LabRptresult::getItemNo)
        //             .collect(Collectors.toList());
        //
        //     //取出 labRptresults 的 itemNO 和 labMapperItems 的 mapperItemCode 相同的数据
        //     List<LabRptresult> collect = labRptresults.stream()
        //             .filter(item -> labMapperItems.stream()
        //                     .anyMatch(labMapperItem -> labMapperItem.getMapperItemCode().equals(item.getItemNo())))
        //             .collect(Collectors.toList());
        //
        //     System.out.println("collect1 = " + collect1);
        // }

        for (LabRptresult labRptresult : list) {
            LabRptresult rptresult = new LabRptresult();
            BeanUtil.copyProperties(labRptresult, rptresult, "id");
            rptresult.setSampleNo(labMaininfo.getSampleNo());

            LambdaQueryWrapper<LabRptresult> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabRptresult::getSampleNo, rptresult.getSampleNo())
                    .eq(LabRptresult::getItemNo, rptresult.getItemNo())
                    .eq(LabRptresult::getRptGroup, rptresult.getRptGroup())
                    .eq(LabRptresult::getSampleda, rptresult.getSampleda())
                    .eq(LabRptresult::getDelFlag, 0);

            boolean b = labRptresultService.saveOrUpdate(rptresult, lambdaQueryWrapper);
        }

        return Result.succ(1, "合并成功", labRptresults);


    }

    @Override
    public Result searchLabMaininfoList(LabMaininfoPageDto maininfoPageDto) {
        LambdaQueryWrapper<LabMaininfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabMaininfo::getDelFlag, 0);
        queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));

        if (StringUtils.isNotBlank(maininfoPageDto.getRptGroup())) {
            queryWrapper.eq(LabMaininfo::getRptGroup, maininfoPageDto.getRptGroup());
        }

        if (StringUtils.isNotBlank(maininfoPageDto.getSampleda())) {
            queryWrapper.eq(LabMaininfo::getSampleda, maininfoPageDto.getSampleda());
        }

        if (!StringUtils.isEmpty(maininfoPageDto.getSampleNo())) {
            List<String> sampleNoList = getSampleNoList(maininfoPageDto.getSampleNo());
            queryWrapper.in(LabMaininfo::getSampleNo, sampleNoList);
        }

        // if (StringUtils.isNotBlank(maininfoPageDto.getSampleNoB()) && StringUtils.isNotBlank(maininfoPageDto.getSampleNoE())) {
        //     queryWrapper.ge(LabMaininfo::getSampleNo, maininfoPageDto.getSampleNoB());
        //     queryWrapper.le(LabMaininfo::getSampleNo, maininfoPageDto.getSampleNoE());
        // }

        if (StringUtils.isNotBlank(maininfoPageDto.getReqNo())) {
            queryWrapper.eq(LabMaininfo::getReqNo, maininfoPageDto.getReqNo());
        }
        if (StringUtils.isNotBlank(maininfoPageDto.getReqDept())) {
            queryWrapper.eq(LabMaininfo::getReqDept, maininfoPageDto.getReqDept());
        }

        if (maininfoPageDto.getIsFilterPatNa()) {
            queryWrapper.isNull(LabMaininfo::getPatNa);
        }

        if (maininfoPageDto.getIsFilterResult()) {
            // notExists
            queryWrapper.notExists("select * from LAB_RPTRESULT where LAB_RPTRESULT.DEL_FLAG = 0 and LAB_RPTRESULT.SAMPLEDA = LAB_MAININFO.SAMPLEDA and LAB_RPTRESULT.RPT_GROUP = LAB_MAININFO.RPT_GROUP and LAB_RPTRESULT.SAMPLE_NO = LAB_MAININFO.SAMPLE_NO");
        }

        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(queryWrapper);

        return Result.succ(labMaininfos);

    }

    @Override
    public Result removeLabMaininfoList(MaininfoDto maininfoDto) {
        List<LabMaininfo> labMaininfoList = maininfoDto.getLabMaininfoList();

        for (LabMaininfo maininfo : labMaininfoList) {
            LambdaQueryWrapper<LabRptresult> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(LabRptresult::getSampleNo, maininfo.getSampleNo())
                    .eq(LabRptresult::getRptGroup, maininfo.getRptGroup())
                    .eq(LabRptresult::getSampleda, maininfo.getSampleda())
                    .eq(LabRptresult::getDelFlag, 0);
            labRptresultMapper.delete(queryWrapper);

            if ("2".equals(maininfoDto.getRadio())) {
                labMaininfoMapper.deleteById(maininfo.getId());
            }


        }
        return Result.succ(1, "删除成功", null);
    }

    @Override
    public Result workSearchMaininfoList(LabMaininfoPageDto maininfoPageDto)  {

        //阿冲写法
        try {
            String where = "";

            if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
                where += " AND t.sampleda >= '" + maininfoPageDto.getSampledaBegin() + "' AND t.sampleda <= '" + maininfoPageDto.getSampledaEnd()+"'";
            }

            if (StringUtils.isNotBlank(maininfoPageDto.getChkdaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getChkdaEnd())) {
                where += " AND t.CHK_TIME >= '" + maininfoPageDto.getChkdaBegin() + "' AND t.CHK_TIME <= '" + maininfoPageDto.getChkdaEnd()+"'";
            }

            String sql = "SELECT COUNT\n" +
                    "\t( DISTINCT t.id ) AS specimenCount,\n" +
                    "\tSUM ( t2.PRICE ) AS totalPrice,\n" +
                    "\tt.RPT_GROUP AS rptGroup \n" +
                    "FROM\n" +
                    "\tLAB_MAININFO t\n" +
                    "\tLEFT JOIN LAB_RPTRESULT t1 ON t1.org_id = '1787488360349155329' \n" +
                    "\tAND ( t1.sampleda = t.sampleda AND t1.RPT_GROUP = t.RPT_GROUP AND t1.SAMPLE_NO = t.SAMPLE_NO AND t1.del_flag = 0 )\n" +
                    "\tLEFT JOIN LAB_FEE_ITEM t2 ON t2.org_id = '1787488360349155329' \n" +
                    "\tAND ( t2.FEE_CODE = t1.FEE_CODE AND t2.del_flag = 0 ) \n" +
                    "WHERE\n" +
                    "\t( t.ORG_ID = '1787488360349155329' ) \n" +
                    "\tAND t.del_flag = 0 \n" +
                    "\tAND t1.del_flag = 0 \n" +
                    "\t"+where+"\n" +
                    "GROUP BY\n" +
                    "\tt.RPT_GROUP";
            System.out.println("sql:"+sql);
            List<Entity> query = Db.use(dataSource).query(sql);
            return Result.succ(1,"查询成功",query);
        }catch (Exception e){
            return Result.fail(e.getMessage());
        }


        // MPJLambdaWrapper<LabMaininfo> wrapper = new MPJLambdaWrapper<>();
        // wrapper.select("COUNT(DISTINCT t.id) AS specimen_count")
        //         .selectSum(LabFeeItem::getPrice, "total_price")
        //         .select(LabMaininfo::getRptGroup)
        //         .leftJoin(LabRptresult.class, p -> p.eq(LabRptresult::getSampleda, LabMaininfo::getSampleda).eq(LabRptresult::getRptGroup, LabMaininfo::getRptGroup)
        //                 .eq(LabRptresult::getSampleNo, LabMaininfo::getSampleNo)
        //                 .eq(LabRptresult::getDelFlag, 0))
        //         .leftJoin(LabFeeItem.class, p -> p.eq(LabFeeItem::getFeeCode, LabRptresult::getFeeCode).eq(LabFeeItem::getDelFlag, 0))
        //         .eq(LabMaininfo::getDelFlag, 0)
        //         .groupBy(LabMaininfo::getRptGroup);
        //
        // if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
        //     wrapper.ge(LabMaininfo::getSampleda, maininfoPageDto.getSampledaBegin());
        //     wrapper.le(LabMaininfo::getSampleda, maininfoPageDto.getSampledaEnd());
        // }
        //
        // if (StringUtils.isNotBlank(maininfoPageDto.getChkdaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getChkdaEnd())) {
        //     wrapper.ge(LabMaininfo::getChkTime, maininfoPageDto.getChkdaBegin());
        //     wrapper.le(LabMaininfo::getChkTime, maininfoPageDto.getChkdaEnd());
        // }
        //
        // List<WorkMainInfoDto> workMainInfoDtos = labMaininfoMapper.selectJoinList(WorkMainInfoDto.class, wrapper);
        // return Result.succ(workMainInfoDtos);
    }

    @Override
    public Result workSearchResultList(LabMaininfoPageDto maininfoPageDto) {
        // 创建 LambdaQueryWrapper
        QueryWrapper<LabRptresult> wrapper = new QueryWrapper<>();

        if ("1".equals(maininfoPageDto.getRadio())){
            // 申请项目设置查询字段
            wrapper.select(
                    "COUNT(DISTINCT id) AS resultCount", // COUNT(DISTINCT t.ID)
                    "RPT_GROUP",                  // RPT_GROUP
                    "FEE_CODE",                     // ITEM_NA
                    "FEE_NAME"                      // ITEM_NO
            );
        }else{
            // 报告项目设置查询字段
            wrapper.select(
                    "COUNT(DISTINCT id) AS resultCount", // COUNT(DISTINCT t.ID)
                    "RPT_GROUP",                  // RPT_GROUP
                    "ITEM_NA",                     // ITEM_NA
                    "ITEM_NO"                      // ITEM_NO
            );
        }

        // 设置过滤条件
        if (StringUtils.isNotBlank(maininfoPageDto.getSampledaBegin()) && StringUtils.isNotBlank(maininfoPageDto.getSampledaEnd())) {
            wrapper.ge("SAMPLEDA", maininfoPageDto.getSampledaBegin());
            wrapper.le("SAMPLEDA", maininfoPageDto.getSampledaEnd());
        }

        wrapper.eq("RPT_GROUP",maininfoPageDto.getRptGroup())
                .eq("DEL_FLAG",0);

        if ("1".equals(maininfoPageDto.getRadio())){
            // 设置分组
            wrapper.groupBy("RPT_GROUP", "FEE_CODE", "FEE_NAME");
        }else{
            // 设置分组
            wrapper.groupBy("RPT_GROUP", "ITEM_NO", "ITEM_NA");
        }

        // 执行查询
        List<LabRptresult> rptresultList = labRptresultMapper.selectList(wrapper);
        return Result.succ(1, "查询成功", rptresultList);
    }

    @Override
    public Result searchMaininfoListByItem(LabMaininfoPageDto maininfoPageDto) {
        MPJLambdaWrapper<LabRptresult> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabRptresult.class);
        //queryWrapper.selectAs(LabMaininfo::getId,LabRptresult::getInstrId);

        queryWrapper.leftJoin(LabMaininfo.class, p -> p.eq(LabMaininfo::getRptGroup, LabRptresult::getRptGroup).eq(LabMaininfo::getSampleda,LabRptresult::getSampleda).eq(LabMaininfo::getSampleNo,LabRptresult::getSampleNo).eq(LabMaininfo::getDelFlag, 0));
        queryWrapper.eq(LabRptresult::getDelFlag, 0);
        queryWrapper.and(p -> p.eq(LabMaininfo::getIsChk, 0).or().isNull(LabMaininfo::getIsChk));

        if (StringUtils.isNotBlank(maininfoPageDto.getRptGroup())) {
            queryWrapper.eq(LabRptresult::getRptGroup, maininfoPageDto.getRptGroup());
        }

        if (StringUtils.isNotBlank(maininfoPageDto.getSampleda())) {
            queryWrapper.eq(LabRptresult::getSampleda, maininfoPageDto.getSampleda());
        }

        if (!StringUtils.isEmpty(maininfoPageDto.getSampleNo())) {
            List<String> sampleNoList = getSampleNoList(maininfoPageDto.getSampleNo());
            queryWrapper.in(LabRptresult::getSampleNo, sampleNoList);
        }

        if (maininfoPageDto.getItemCodes() != null && maininfoPageDto.getItemCodes().size() > 0){
            queryWrapper.in(LabRptresult::getItemNo, maininfoPageDto.getItemCodes());
        }

        queryWrapper.and(p -> p.eq(LabRptresult::getTestResult, "").or().isNull(LabRptresult::getTestResult).or().eq(LabRptresult::getTestResult, "未做"));

        // if (StringUtils.isNotBlank(maininfoPageDto.getSampleNoB()) && StringUtils.isNotBlank(maininfoPageDto.getSampleNoE())) {
        //     queryWrapper.ge(LabMaininfo::getSampleNo, maininfoPageDto.getSampleNoB());
        //     queryWrapper.le(LabMaininfo::getSampleNo, maininfoPageDto.getSampleNoE());
        // }

        // if (StringUtils.isNotBlank(maininfoPageDto.getReqNo())) {
        //     queryWrapper.eq(LabMaininfo::getReqNo, maininfoPageDto.getReqNo());
        // }
        // if (StringUtils.isNotBlank(maininfoPageDto.getReqDept())) {
        //     queryWrapper.eq(LabMaininfo::getReqDept, maininfoPageDto.getReqDept());
        // }
        //
        // if (maininfoPageDto.getIsFilterPatNa()) {
        //     queryWrapper.isNull(LabMaininfo::getPatNa);
        // }

        // if (maininfoPageDto.getIsFilterResult()) {
        //     // notExists
        //     queryWrapper.notExists("select * from LAB_RPTRESULT where LAB_RPTRESULT.DEL_FLAG = 0 and LAB_RPTRESULT.SAMPLEDA = LAB_MAININFO.SAMPLEDA and LAB_RPTRESULT.RPT_GROUP = LAB_MAININFO.RPT_GROUP and LAB_RPTRESULT.SAMPLE_NO = LAB_MAININFO.SAMPLE_NO");
        // }

        List<LabRptresult> labRptresults = labRptresultMapper.selectList(queryWrapper);

        return Result.succ(labRptresults);
    }


    private List<String> getSampleNoList(String sampleNo) {
        List<String> stringList = new ArrayList<>();
        String[] split = sampleNo.split(",");
        for (String sp : split) {
            boolean contains = sp.contains("-");
            if (contains) {
                String[] split1 = sp.split("-");
                boolean digits = NumberUtils.isDigits(split1[0]);
                boolean digits1 = NumberUtils.isDigits(split1[1]);
                if (digits && digits1) {
                    Integer f = Integer.valueOf(split1[0]);
                    Integer s = Integer.valueOf(split1[1]);
                    for (int i = f; i <= s; i++) {
                        stringList.add(String.valueOf(i));
                    }
                }
            } else {
                stringList.add(sp);
            }
        }
        return stringList.stream().distinct().collect(Collectors.toList());
    }

}
